<template>
  <div class="container">
    <div class="app-container">
      <el-dialog :visible.sync="showRoleDialog" title="分配角色">
        <!-- 弹层内容 -->
        <!-- checkbox -->
        <el-checkbox-group v-model="roleIds">
          <!-- 放置n个的checkbox  要执行checkbox的存储值 item.id-->
          <el-checkbox
            v-for="item in roleList"
            :key="item.id"
            :label="item.id"
          >{{ item.name }}</el-checkbox>
        </el-checkbox-group>
        <el-row slot="footer" type="flex" justify="center">
          <el-col :span="6">
            <el-button type="primary" size="mini" @click="btnRoleOK">确定</el-button>
            <el-button size="mini" @click="showRoleDialog = false">取消</el-button>
          </el-col>
        </el-row>
      </el-dialog>
      <import-excel :show-excel-dialog.sync="showExcelDialog" @uploadSuccess="onSuccess" />
      <div class="left">
        <el-input v-model="queryParams.keyword" placeholder="输入员工姓名全员搜索" prefix-icon="el-icon-search" type="text" size="small" style="margin-bottom: 10px;" @input="changeValue" />
        <el-tree ref="deptTree" node-key="id" :data="departmentList" :props="defaultProps" default-expand-all :expand-on-click-node="false" highlight-current @current-change="selectNode" />
      </div>
      <div class="right">
        <el-row type="flex" justify="end" class="opeate-tools">
          <el-button v-permission="'add-employee'" type="primary" size="mini" @click="$router.push('/employee/detail')">添加员工</el-button>
          <el-button size="mini" @click="showExcelDialog = true">导入excel</el-button>
          <el-button size="mini" @click="exportEmployee">导出excel</el-button>
        </el-row>
        <el-table :data="tableData" style="width: 100%">
          <el-table-column prop="staffPhoto" label="头像" align="center">
            <template v-slot="{row}">
              <img v-if="row.staffPhoto" :src="row.staffPhoto" style="width: 30px;height: 30px;border-radius: 50%;" alt="">
              <span v-else class="username">{{ row.username?.charAt(2) }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="username" label="姓名" />
          <el-table-column prop="mobile" label="手机号" width="120px" sortable />
          <el-table-column prop="workNumber" label="工号" width="120px" sortable />
          <el-table-column prop="formOfEmployment" label="聘用形式">
            <template v-slot="{row}">
              {{ row.formOfEmployment === 1 ? '正式' : '非正式' }}
            </template></el-table-column>
          <el-table-column prop="departmentName" label="部门" />
          <el-table-column prop="timeOfEntry" label="入职时间" width="120px" sortable />
          <el-table-column label="操作" width="280px">
            <template v-slot="{row}">
              <el-button type="text" size="mini" @click="$router.push(`/employee/detail?id=${row.id}`)">查看</el-button>
              <el-button type="text" size="mini" @click="assignrole(row.id)">角色</el-button>
              <el-popconfirm title="确认删除该行数据吗？" @onConfirm="confirmDel(row.id)">
                <el-button slot="reference" style="margin-left:10px" size="mini" type="text">删除</el-button>
              </el-popconfirm>
            </template>
          </el-table-column>

        </el-table>
        <el-row type="flex" justify="end" align="middle" style="height: 60px">
          <el-pagination background layout="total,prev, pager, next" :total="total" :current-page="queryParams.page" :page-size="queryParams.pagesize" @current-change="handleCurrentChange" />
        </el-row>
      </div>
    </div>
  </div>
</template>
<script>
import { getDepartment } from '@/api/department'
import { transListToTreeData } from '@/utils'
import { getemployeeList, exportemployee, deleteemployee, getemployee, assignRoles } from '@/api/employee'
import FileSaver from 'file-saver'
import importExcel from './components/import-excel.vue'
import { getEnableRole } from '@/api/role'
export default {
  name: 'Employee',
  components: { importExcel },
  data() {
    return {
      departmentList: [],
      defaultProps: {
        label: 'name',
        value: 'children'
      },
      queryParams: {
        departmentId: null,
        page: 1,
        pagesize: 5,
        keyword: ''
      },
      tableData: [],
      total: 0,
      timer: null,
      showExcelDialog: false,
      roleList: [],
      showRoleDialog: false,
      roleIds: []
      // currentUserId: null // 用来记录当前点击的用户id
    }
  },
  created() {
    this.getDepartment()
  },
  methods: {
    async getDepartment() {
      this.departmentList = await getDepartment()
      this.departmentList = transListToTreeData(this.departmentList, 0)
      this.queryParams.departmentId = this.departmentList[0].id
      this.$nextTick(() => {
        this.$refs.deptTree.setCurrentKey(this.queryParams.departmentId)
      })
      this.getemployeeList()
    },
    selectNode(node) {
      this.queryParams.departmentId = node.id
      this.queryParams.page = 1
      this.getemployeeList()
    },
    async getemployeeList() {
      const { rows, total } = await getemployeeList(this.queryParams)
      this.tableData = rows
      this.total = total
      console.log(this.tableData)
    },
    handleCurrentChange(val) {
      this.queryParams.page = val
      this.getemployeeList()
    },
    changeValue(value) {
      // console.log(this.queryParams.keyword)
      clearInterval(this.timer)
      this.timer = setTimeout(() => {
        this.queryParams.page = 1
        this.getemployeeList()
      }, 300)
    },
    async exportEmployee() {
      const result = await exportemployee()
      FileSaver.saveAs(result, '员工信息.xlsx')
    },
    onSuccess() {
      this.getemployeeList()
    },
    async confirmDel(id) {
      console.log(id)
      await deleteemployee(id)
      this.$message.success('删除成功')
      if (this.tableData.length === 1 && this.queryParams.page > 1) {
        this.queryParams.page--
      }
      this.getemployeeList()
    },
    async getEnableRole() {
      const res = await getEnableRole()
      this.roleList = res
      console.log('rolelist', res)
    },
    async assignrole(id) {
      this.getEnableRole()
      this.currentUserId = id

      const { roleIds } = await getemployee(id)
      this.roleIds = roleIds
      this.showRoleDialog = true
    },
    async btnRoleOK() {
      await assignRoles(this.currentUserId, this.roleIds)
      this.$message.success('分配角色成功')
      this.showRoleDialog = false
    }
  }
}
</script>

<style lang="scss" scoped>
.app-container {
  background: #fff;
  display: flex;
  .left {
    width: 280px;
    padding: 20px;
    border-right: 1px solid #eaeef4;
  }
  .right {
    flex: 1;
    padding: 20px;
    .opeate-tools {
      margin:10px ;
    }
    .username {
      height: 30px;
      width: 30px;
      line-height: 30px;
      text-align: center;
      border-radius: 50%;
      color: #fff;
      background: #04C9BE;
      font-size: 12px;
      display:inline-block;
    }
  }
}

</style>
